<template>
  <div class="login">
    <el-card style="width: 400px">
      <template #header>
        <h2>登录</h2>
      </template>

      <el-form ref="formRef" label-position="top" :rules="rules" :model="form">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="form.password" />
        </el-form-item>
        <el-form-item>
          <el-button size="large" type="primary" @click="doLogin">登录</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>
<script setup>
import { useRouter } from 'vue-router';

import { reactive, shallowRef } from 'vue';

import { useLogin } from './login';

const router = useRouter();

// 表单数据绑定
const form = reactive({
  username: 'root',
  password: '123123',
});

// 编写验证规则
const rules = {
  username: [{ required: true, message: '用户名必须填写', trigger: 'change' }],
  password: [{ required: true, message: '密码必须填写', trigger: 'change' }],
};

const formRef = shallowRef(null);

// 判断是否登录，如果登录就跳转
if (localStorage.token) {
  router.push({ name: 'UsersIndex' });
}

// 登录
const login = useLogin(router);
const doLogin = async () => {
  login(formRef, { username: form.username, password: form.password });
};
</script>

<style lang="scss">
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  position: fixed;
  top: 0;
  bottom: 0;
  right: 0;
  left: 0;
}
</style>
